﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Renci.SshNet;
using System.IO;
using System.Collections;
using System.Net.Mail;

namespace SY.SFTPHelper
{
    public class SFTPHelper
    {
        #region 字段或属性
         private SftpClient sftp;
         /// <summary>
         /// SFTP连接状态
         /// </summary>
         public bool Connected { get { return sftp.IsConnected; } }
         #endregion
 
         #region 构造
         /// <summary>
         /// 构造
         /// </summary>
         /// <param name="ip">IP</param>
         /// <param name="port">端口</param>
         /// <param name="user">用户名</param>
         /// <param name="pwd">密码</param>
         public SFTPHelper(string ip, string port, string user, string pwd)
         {
             sftp = new SftpClient(ip, Int32.Parse(port), user, pwd);
         }
         #endregion


 
         #region 连接SFTP
         /// <summary>
         /// 连接SFTP
         /// </summary>
         /// <returns>true成功</returns>
         public bool Connect()
         {
             try
             {
                 if (!Connected)
                 {
                     sftp.Connect();
                 }
                 return true;
             }
             catch (Exception ex)
             {
                 // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("连接SFTP失败，原因：{0}", ex.Message));
                 //throw new Exception(string.Format("连接SFTP失败，原因：{0}", ex.Message));
                 WriteLog("连接SFTP失败，原因:" + ex.Message);
                 SendMailUse("连接SFTP失败，原因：" + ex.Message, "BIBJ Sales report");
                 return false ;
                 
             }
         }
         #endregion
 
         #region 断开SFTP
         /// <summary>
         /// 断开SFTP
         /// </summary> 
         public void Disconnect()
         {
             try
             {
                 if (sftp != null && Connected)
                 {
                     sftp.Disconnect();
                 }
             }
             catch (Exception ex)
             {
                 // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("断开SFTP失败，原因：{0}", ex.Message));
                 //throw new Exception(string.Format("断开SFTP失败，原因：{0}", ex.Message));
                 WriteLog("断开SFTP失败，原因:" + ex.Message);
                 SendMailUse("断开SFTP失败，原因：" + ex.Message, "BIBJ Sales report");
             }
         }
         #endregion
 
         #region SFTP上传文件
         /// <summary>
         /// SFTP上传文件
         /// </summary>
         /// <param name="localPath">本地路径</param>
         /// <param name="remotePath">远程路径</param>
         public void Put(string localPath, string remotePath)
         {
             try
             {
                 using (var file = File.OpenRead(localPath))
                 {
                     Connect();
                     sftp.UploadFile(file, remotePath);
                     Disconnect();
                 }
             }
             catch (Exception ex)
             {
                 // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件上传失败，原因：{0}", ex.Message));
                // throw new Exception(string.Format("SFTP文件上传失败，原因：{0}", ex.Message));
                 WriteLog("SFTP文件上传失败，原因:" + ex.Message);
                 SendMailUse("SFTP文件上传失败，原因：" + ex.Message, "BIBJ Sales report");
             }
         }
         #endregion
 
         #region SFTP获取文件
         /// <summary>
         /// SFTP获取文件
         /// </summary>
         /// <param name="remotePath">远程路径</param>
         /// <param name="localPath">本地路径</param>
         public void Get(string remotePath, string localPath)
         {
             try
             {
                 Connect();
                 var byt = sftp.ReadAllBytes(remotePath);
                 Disconnect();
                 File.WriteAllBytes(localPath, byt);
             }
             catch (Exception ex)
             {
                 // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件获取失败，原因：{0}", ex.Message));
                 //throw new Exception(string.Format("SFTP文件获取失败，原因：{0}", ex.Message));
                 WriteLog("SFTP文件获取失败，原因:" + ex.Message);
                 SendMailUse("SFTP文件获取失败，原因：" + ex.Message, "BIBJ Sales report");
             }
 
         }
         #endregion
 
         #region 删除SFTP文件
         /// <summary>
         /// 删除SFTP文件 
         /// </summary>
         /// <param name="remoteFile">远程路径</param>
         public void Delete(string remoteFile)
         {
             try
             {
                 Connect();
                 sftp.Delete(remoteFile);
                 Disconnect();
             }
             catch (Exception ex)
             {
                 // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件删除失败，原因：{0}", ex.Message));
                 //throw new Exception(string.Format("SFTP文件删除失败，原因：{0}", ex.Message));
                 WriteLog("SFTP文件删除失败，原因:" + ex.Message);
                 SendMailUse("SFTP文件删除失败，原因：" + ex.Message, "BIBJ Sales report");
             }
         }
         #endregion
 
         #region 获取SFTP文件列表
         /// <summary>
         /// 获取SFTP文件列表
         /// </summary>
         /// <param name="remotePath">远程目录</param>
         /// <param name="fileSuffix">文件后缀</param>
         /// <returns></returns>
         public ArrayList GetFileList(string remotePath, string fileSuffix)
         {
             try
             {
                 Connect();
                 var files = sftp.ListDirectory(remotePath);
                 Disconnect();
                 var objList = new ArrayList();
                 foreach (var file in files)
                 {
                     string name = file.Name;
                     if (name.Length > (fileSuffix.Length + 1) && fileSuffix == name.Substring(name.Length - fileSuffix.Length))
                     {
                         objList.Add(name);
                     }
                 }
                 return objList;
             }
             catch (Exception ex)
             {
                 //TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
                 //throw new Exception(string.Format("SFTP文件列表获取失败，原因：{0}", ex.Message));
                 WriteLog("SFTP文件列表获取失败，原因:"+ ex.Message);
                 SendMailUse("SFTP文件列表获取失败，原因：" + ex.Message, "BIBJ Sales report");
                 var objList = new ArrayList();
                 return objList;
             }
         }
         #endregion
 
         #region 移动SFTP文件
         /// <summary>
         /// 移动SFTP文件
         /// </summary>
         /// <param name="oldRemotePath">旧远程路径</param>
         /// <param name="newRemotePath">新远程路径</param>
         public void Move(string oldRemotePath, string newRemotePath)
         {
             try
             {
                 Connect();
                 sftp.RenameFile(oldRemotePath, newRemotePath);
                 Disconnect();
             }
             catch (Exception ex)
             {
                 // TxtLog.WriteTxt(CommonMethod.GetProgramName(), string.Format("SFTP文件移动失败，原因：{0}", ex.Message));
                 SendMailUse("SFTP文件移动失败，原因：" + ex.Message, "BIBJ Sales report");
             }
         }
         #endregion

         public  void WriteLog(string strLog)
         {
             string sFilePath = "c:\\" + DateTime.Now.ToString("yyyyMM");
             string sFileName = "rizhi" + DateTime.Now.ToString("dd") + ".log";
             sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
             if (!Directory.Exists(sFilePath))//验证路径是否存在
             {
                 Directory.CreateDirectory(sFilePath);
                 //不存在则创建
             }
             FileStream fs;
             StreamWriter sw;
             if (File.Exists(sFileName))
             //验证文件是否存在，有则追加，无则创建
             {
                 fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
             }
             else
             {
                 fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
             }
             sw = new StreamWriter(fs);
             sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + " --- " + strLog);
             sw.Close();
             fs.Close();
         }
         public  void SendMailUse(string text, string FZT)
         {

             string host = "smtp.exmail.qq.com";// 邮件服务器smtp.163.com表示网易邮箱服务器     smtp.exmail.qq.com   smtprelay1.thermofisher.com 
             string userName = "zhichao.wang@ipoodee.com";// 发送端账号   k3@thermofisher.com   zhichao.wang@ipoodee.com  18600656671@163.com
             string password = "wangzhichao2014";// 发送端密码(这个客户端重置后的密码) 

             SmtpClient client = new SmtpClient();
             client.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式    
             client.Host = host;//邮件服务器
             client.UseDefaultCredentials = true;
             client.Credentials = new System.Net.NetworkCredential(userName, password);//用户名、密码

             //////////////////////////////////////
             string strfrom = userName;


             string subject = FZT;//邮件的主题            


             System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
             msg.From = new MailAddress(strfrom, "k3");

             //msg.To.Add("361737759@qq.com");
             foreach (string str in System.IO.File.ReadAllLines("C:\\K3\\mailtxt.txt", Encoding.Default))
             {
                 msg.To.Add(str);

             }


             msg.Subject = subject;//邮件标题   
             msg.Body = text;//邮件内容      
             msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码   
             msg.IsBodyHtml = true;//是否是HTML邮件   
             msg.Priority = MailPriority.High;//邮件优先级   


             try
             {
                 client.Send(msg);

             }
             catch (System.Net.Mail.SmtpException ex)
             {
                 Console.WriteLine(ex.Message + "发送邮件出错", "邮件提醒");


                 Console.WriteLine(ex.Message, "发送邮件出错");
                 Environment.Exit(0);

             }
         }
    }
}
